package com.xzx.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 分布式客户端，监听服务端上下线
 * @author xinzhixuan
 * @version V1.0
 * @date 2019/8/12 22:39
 */
public class DistributeClient {
    private String connectString = "localhost:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zooKeeperClient;

    public static void main(String[] args) throws Exception {
        DistributeClient client = new DistributeClient();
        client.getConnection();
        client.getServerNode();
        client.doBusiness();
    }

    private void doBusiness() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void getServerNode() throws KeeperException, InterruptedException {
        List<String> servers = new ArrayList<>();
        List<String> list = zooKeeperClient.getChildren("/servers", true);
        for (String child : list) {
            byte[] data = zooKeeperClient.getData("/servers/" + child, false, null);
            servers.add(new String(data));
        }
        System.out.println("online servers:" + servers);
    }

    private void getConnection() throws IOException {
        zooKeeperClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event);
                try {
                    getServerNode(); // 只要已启动，这里会理解执行一次
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
